package com.example.workweixinwebhook.controller;

import com.example.workweixinwebhook.utils.AesException;
import com.example.workweixinwebhook.utils.WXBizMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: zhouyuehan
 * @Date: 2023/11/28 16:12
 */
@Slf4j
@RestController
@RequestMapping("/work/weixin/webhook")
public class TestController {

    @Value("${weixin.token}")
    String token;

    @Value("${weixin.corpId}")
    String corpId;

    @Value("${weixin.encodingAESKey}")
    String encodingAESKey;

    @RequestMapping("/receive")
    public String receive(@RequestBody(required = false) String data,
                          @RequestParam("msg_signature") String msgSignature,
                          @RequestParam("timestamp") String timestamp,
                          @RequestParam("nonce") String nonce,
                          @RequestParam(value = "echostr", required = false) String echostr) {

        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
            String ret;
            if (echostr != null) {
                ret = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
                log.info("收到企业微信开启回调通知，返回：{}", ret);
                return ret;
            } else {
                String sMsg = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, data);
                log.info("收到企业微信回调，内容：{}", sMsg);
                return "success";
            }
        } catch (AesException e) {
            log.error("配置不正确", e);
        }
        return null;
    }
}
